var app = getApp()
//常量数据配置
var ConstantData = require('../../common/constant_data.js')
var common = require('../../common/common.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pcode: '',
    phonenum: '',
    VerifyCode: "获取验证码",
    loginBtnTxt: "登 录",
    loginBtnStatus: true,
    card_number: '',
    pt: '',
    checked: true,
    checkedVal: [1],
    getPhoneStat: true, //获取验证码按钮的限制
    showDialog: false,
    phoneType: '',
  },

  toViewLeaseProtocol: function () {
    wx.navigateTo({
      url: '../../pkgBak/pages/help/lease/lease',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var pt = options.pt
    if (pt == 'time_card_detail') {
      var cardNumber = options.cn
      this.setData({
        pt: 'time_card_detail',
        card_number: cardNumber
      })
    }

    if (!pt) {
      pt = '';
    }
    
    if (app.globalData.defCheckAgreeService) {
      this.setData({
        pt: pt,
        checked: true,
        checkedVal: [1]
      })
    }else {
      this.setData({
        pt: pt,
        checked: false,
        checkedVal: []
      })
    }
   
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    if (app.globalData.defCheckAgreeService) {
      this.setData({
        checked: true,
        checkedVal: [1]
      })
    }else {
      this.setData({
        checked: false,
        checkedVal: []
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (app.globalData.defCheckAgreeService) {
      this.setData({
        checked: true,
        checkedVal: [1]
      })
    }else {
      this.setData({
        checked: false,
        checkedVal: []
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    if (app.globalData.defCheckAgreeService) {
      this.setData({
        checked: true,
        checkedVal: [1]
      })
    }else {
      this.setData({
        checked: false,
        checkedVal: []
      })
    }
    this.setData({
      VerifyCode: "获取验证码",
      loginBtnTxt: "登 录",
      loginBtnStatus: true,
      getPhoneStat: true //获取验证码按钮的限制
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**  
   * 获取用户手机号
   */
  getPhoneNumber: function(e) {
    var that = this;
    if (e.detail.errMsg.indexOf('user deny') != -1) {
      return;
    } else {
      //解密数据并登录成功
      app.executeRequest(function(header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/auth/wxPhoneAuthLogin',
          method: 'post',
          header: header,
          data: {
            iv: encodeURIComponent(e.detail.iv),
            encryptedData: encodeURIComponent(e.detail.encryptedData)
          },
          success: function(res) {
            if (res.data.result === 0) {
              //登录成功
              wx.showToast({
                title: '登录成功',
                icon: 'none'
              })

              wx.setStorageSync('nophone', '2');
              app.globalData.loginData.nophone = 2;
              var pt = that.data.pt
              setTimeout(() => {
                if (pt == 'time_card_detail') {
                  //包时卡详情
                  var cardNumber = that.data.card_number
                  wx.navigateTo({
                    url: '../../pkgBak/pages/time_card/detail/time_card_detail?cn=' + cardNumber,
                  })
                  return
                } else if (pt == 'outpatient_add_employer') {
                  //爱心租赁
                  wx.redirectTo({
                    url: '../outpatient_service/manage_employer/manage_employer',
                  })
                } else if (pt == 'outpatient_manage_careworker') {
                  //门诊爱心租赁护工管理
                  wx.redirectTo({
                    url: '../outpatient_service/manage_careworker/manage_careworker',
                  })
                } else if (pt == 'user_center') {
                  //个人中心
                  wx.redirectTo({
                    url: '../user_center/user_center',
                  })
                } else if (pt == 'deposit_record') {
                  //押金记录
                  wx.redirectTo({
                    url: '../user_record/deposit/user_deposit',
                  })
                } else if (pt == 'no_return_blue_timeout') {
                  //押金记录
                  wx.redirectTo({
                    url: '../index/index?pt=no_return_blue_timeout',
                  })
                } else if (pt == 'scan') {
                  wx.redirectTo({
                    url: '../index/index?pt=scan',
                  });
                } else {
                  wx.reLaunch({
                    url: '../index/index',
                  });
                }
              }, 1000)
            } else if (res.data.result === 4) {
              wx.showToast({
                title: res.data.description,
                icon: "none"
              });
            } else {
              wx.showToast({
                title: '登录失败',
                image: '/image/gantan.png'
              })
            }
          }
        });

      });
    }
  },
  setPcode: function(e) {
    this.data.pcode = e.detail;
  },
  setPhonenum: function(e) {
    console.log(33,e)
    this.data.phonenum = e.detail;
    this.setData({
      phonenum:e.detail
    })
  },
  getPhoneCode: function(e) {
    console.log("---phonenum=" + this.data.phonenum)
    if (this.data.phonenum != '' && this.data.getPhoneStat) {
      this.setData({
        getPhoneStat: false
      })
      var total_micro_second = 60 * 1000;
      //验证码倒计时
      count_down(this, total_micro_second);
      var url = "/lease_msg/tcpcode";
      if (e.target.id == "voiceCode") {
        url = "/lease_msg/tcyycode";
      }
      var phonenum = this.data.phonenum;
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + url,
        method: 'post',
        header: app.getHeader(),
        data: {
          phonenum: phonenum,
          phone: phonenum
        },
        success: function(res) {
          console.log("发送短信成功")
          console.log(res)
          wx.showToast({
            title: '发送成功',
            icon: 'none'
          })
        },
        fail: function(res) {
          console.log("发送短信失败")
          console.log(res)
          wx.showToast({
            title: '发送失败',
            icon: 'none'
          })
        }
      })
    } else if (!this.data.phonenum) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
    } else {
      wx.showToast({
        title: '请稍后再重新发送',
        icon: 'none'
      })
    }
  },
  checkboxChange: function(e) {
    this.data.checkedVal = e.detail.value
  },

  voicePhoneCode: function(e) {
    var that = this;
    if (this.data.phonenum == '') {
      wx.showToast({
        title: '请输入手机号'
      })
      return;
    } else if (this.data.phonenum.length != 11) {
      wx.showToast({
        title: '手机号位数不正确'
      })
      return;
    }

    wx.showModal({
      title: '温馨提示',
      content: '我们将通过电话方式给您播放验证码，请注意接听来电并记录验证码',
      success: function(res) {
        if (res.confirm) {
          that.getPhoneCode(e);
        } else if (res.cancel) {}
      }
    })
  },

  userLogin: function() {
    if (!this.data.loginBtnStatus) {
      return;
    }

    if (this.data.pcode == '' || this.data.phonenum == '') {
      wx.showToast({
        title: this.data.phonenum != '' ? '验证码不能为空' : '手机号不能为空',
      })
      return
    }
  

    var that = this
    if (this.data.pcode != '' && this.data.phonenum != '') {
      that.setData({
        loginBtnStatus: false
      })
      var total_micro_second = 50 * 1000;
      loginSecondCountDown(this, total_micro_second)
      var code = this.data.pcode;
      var phonenum = this.data.phonenum;
      this.loginAuth(phonenum, code);
    } else {
      wx.showToast({
        title: this.data.phonenum != '' ? '验证码为空' : '手机号为空',
      })
    }
  },
  loginAuth: function(phone, pcode) {
    var that = this;

    wx.checkSession({

      success: function() {
        console.log("loginSuccess----------登录中")
        that.loginReuest('', phone, pcode)
      },
      fail: function() {
        //登录态过期      
        console.log("onReday loginAuth-------------->")
        that.wxLogin(phone, pcode);
      }

    })

  },
  /**
   * 微信登录
   */
  wxLogin: function(phone, pcode) {
    var that = this

    //调用登录接口
    wx.login({
      success: function(res) {
        console.log(res);
        if (res.code) {
          that.loginReuest(res.code, phone, pcode)
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
          var logDesc = JSON.stringify(res);
          var data = {
            phone: phone,
            logType: 'login_fail',
            logTypeVal: 1001,
            logDesc: logDesc
          }

          common.debugInfo(data, app.getHeader())

          wx.showToast({
            title: '登录失败,请重试',
          })

          wx.reLaunch({
            url: '../index/index',
          })

        }
      },
      fail: function(res) {

        var logDesc = JSON.stringify(res);
        var data = {
          phone: phone,
          logType: 'login_fail',
          logTypeVal: 1000,
          logDesc: logDesc
        }

        common.debugInfo(data, app.getHeader())

        wx.showToast({
          title: '登录失败,请重试',
        })

        wx.reLaunch({
          url: '../index/index',
        })

      },
      complete: function(res) {
        var logDesc = JSON.stringify(res);
        var data = {
          phone: phone,
          logType: 'login_complete',
          logTypeVal: 1000,
          logDesc: logDesc
        }

        common.debugInfo(data, app.getHeader())
      }
    });
  },
  loginReuest: function(code, phone, pcode) {
    var that = this

    app.executeRequest(function(header) {

      //发起网络请求
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/auth/login_wx',
        method: 'post',
        header: header,
        data: {
          code: code,
          phone: phone,
          pcode: pcode
        },
        success: function(res) {

          var logDesc = JSON.stringify(res);
          var data = {
            phone: phone,
            logType: 'login_suc',
            logTypeVal: 1001,
            logDesc: logDesc
          }

          common.debugInfo(data, app.getHeader())


          var result = res.data.result;
          if (result == 0) {
            if (res.data.data.result && res.data.data.result != 0) {
              wx.showToast({
                title: res.data.data.description,
              });

              that.setData({
                loginBtnTxt: "重新登录",
                loginBtnStatus: true
              });
              return;
            }

            try {
              if (res.data.data.pass) {
                wx.setStorageSync('pass', res.data.data.pass);
                wx.setStorageSync('temp', res.data.data.temp);
                wx.setStorageSync('ltime', res.data.data.ltime);
                wx.setStorageSync('cpass', res.data.data.cpass);
                wx.setStorageSync('uuid', res.data.data.uuid);
                wx.setStorageSync('nophone', res.data.data.nophone);
                wx.setStorageSync('user_id', res.data.data.uid);
                app.globalData.loginData = res.data.data;
              }
            } catch (e) {}

            that.getBaseConfig();

            var pt = that.data.pt
            if (pt == 'time_card_detail') {
              //包时卡详情
              var cardNumber = that.data.card_number
              wx.navigateTo({
                url: '../../pkgBak/pages/time_card/detail/time_card_detail?cn=' + cardNumber,
              })
              return
            } else if (pt == 'outpatient_add_employer') {
              //爱心租赁
              wx.redirectTo({
                url: '../outpatient_service/manage_employer/manage_employer',
              })
            } else if (pt == 'outpatient_manage_careworker') {
              //门诊爱心租赁护工管理
              wx.redirectTo({
                url: '../outpatient_service/manage_careworker/manage_careworker',
              })
            } else if (pt == 'user_center') {
              //个人中心
              wx.redirectTo({
                url: '../user_center/user_center',
              })
            } else if (pt == 'deposit_record') {
              //押金记录
              wx.redirectTo({
                url: '../user_record/deposit/user_deposit',
              })
            } else if (pt == 'no_return_blue_timeout') {
              //押金记录
              wx.redirectTo({
                url: '../index/index?pt=no_return_blue_timeout',
              })
            } else if (pt == 'scan') {
              wx.redirectTo({
                url: '../index/index?pt=scan',
              });
            } else {
              wx.reLaunch({
                url: '../index/index',
              });
            }
          } else {
            if (result == 2) {
              wx.navigateTo({
                url: '../login/login',
              });
            } else {
              wx.showToast({
                title: res.data.description
              });
              that.setData({
                loginBtnTxt: "重新登录",
                loginBtnStatus: true
              });
            }
          }
        }
      })

    });

  },
  getBaseConfig:function() {
    let that=this
    app.executeRequest(function (header) {
      const sysInfo = wx.getSystemInfoSync()
      console.log('手机类型',sysInfo)
      let phoneType=sysInfo.model
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/support/base_config',
        method: 'post',
        header: header,
        data: {
          phoneType: phoneType
        },
        success: function (res) {
          let netErr = app.handleRes(res, that);
          if (netErr) {
            that.setData({
              loading_show: false
            })
            return
          }
          var config = JSON.parse(res.data)

          // 如果服务器返回了登录页面默认是否勾选同意按钮的配置，则将服务器下发的配置覆盖保存到本地全局配置
          if (config.defCheckAgreeService != undefined) {
            app.globalData.defCheckAgreeService = config.defCheckAgreeService == 1
          }

          if (config.miniBeeConfig) {
            app.globalData.miniBeeConfig = config.miniBeeConfig
          } else {
            app.globalData.miniBeeConfig = null
          }
        }
      })

    });
  },
  
  toggleDialog:function(){
 
  },
  closeConfirm:function() {
    this.setData({
      showDialog:false
    }) 
  },
  toLogin:function() {
    if (this.data.pcode == '' || this.data.phonenum == '') {
      wx.showToast({
        title: this.data.phonenum != '' ? '验证码不能为空' : '手机号不能为空',
      })
      return
    }
    if (this.data.checkedVal.length > 0) {
      this.userLogin()
      return  
    }
    this.setData({
      showDialog: true
    })
  },
  confirmLogin:function() {
    this.setData({
      checkedVal: [1],
      checked: true,
      showDialog: false
    })

    this.userLogin()
  }

})

//登录倒计时
function loginSecondCountDown(that, total_micro_second) {
  if (that.data.loginBtnStatus) {
    console.log("重新登录")
    return;
  }
  if (total_micro_second <= 0) {
    that.setData({
      loginBtnTxt: "重新登录",
      loginBtnStatus: true
    });
    // timeout则跳出递归
    return;
  }
  // 渲染倒计时时钟
  that.setData({
    loginBtnTxt: "登录中,请稍后...(" + date_format(total_micro_second) + " 秒)"
  });

  setTimeout(function() {
    // 放在最后--
    total_micro_second -= 1000;
    loginSecondCountDown(that, total_micro_second);
  }, 1000)
}

function count_down(that, total_micro_second) {
  if (total_micro_second <= 0) {
    that.setData({
      VerifyCode: "重新发送",
      getPhoneStat: true
    })
    // timeout则跳出递归
    return;
  }
  // 渲染倒计时时钟
  that.setData({
    VerifyCode: date_format(total_micro_second) + " 秒"
  });
  setTimeout(function() {
    // 放在最后--
    total_micro_second -= 1000;
    count_down(that, total_micro_second);
  }, 1000)
}

// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  var sec = fill_zero_prefix(second); // equal to => var sec = second % 60;
  return sec;
}
// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}